<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="addDiavisible"
      width="70%"
      @close="cancel"
      @opened="beforeopen"
    >
      <el-form
        :model="form"
        ref="formRef"
        :rules="formRules"
        label-width="110px"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :lg="12" :xl="12">
            <el-form-item label="团队名" prop="groupId">
              <el-select v-model="form.groupId" style="width: 100%">
                <el-option
                  v-for="item in teamName"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xl="12">
            <el-form-item label="签约医生">
              <el-input v-model="hospitalUserId" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :lg="12" :xl="12">
            <el-form-item label="服务开始时间" prop="serviceStartTime">
              <el-date-picker
                v-model="form.serviceStartTime"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xl="12">
            <el-form-item label="服务结束时间" prop="serviceEndTime">
              <el-date-picker
                v-model="form.serviceEndTime"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :lg="12" :xl="12">
            <el-form-item label="居民姓名" prop="residentName">
              <el-input v-model="form.residentName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xl="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" @blur="sexAndAge"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :lg="12" :xl="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" style="width: 100%">
                <el-option
                  v-for="item in sex"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xl="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="住址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>

        <!-- 表格 -->
        <el-table
          class="mt-20"
          ref="tableRef"
          :data="tableData"
          border
          stripe
          @selection-change="tableSelect"
        >
          <el-table-column type="index" label="序号" align="center">
          </el-table-column>
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="id" label="服务包ID" align="center">
          </el-table-column>
          <el-table-column prop="name" label="服务包名称" align="center">
          </el-table-column>
          <el-table-column
            prop="type"
            label="类型"
            align="center"
            :formatter="formatType"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            header-align="center"
            align="center"
            width="200px"
          >
            <template slot-scope="scope">
              <HButton @click="check(scope.row)" type="check" size="mini"
                >查看详情</HButton
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="20" class="buttomItem">
          <el-col :lg="12" :xl="12">
            <el-form-item label="居民手机号">
              <el-input v-model="form.residentPhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xl="12">
            <el-form-item label="手机验证码">
              <el-input v-model="form.phoneNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="签约照片">
          <el-upload
            class="upload-demo"
            action=""
            list-type="picture-card"
            :before-remove="beforeRemove"
            :on-change="onprogress"
            accept=".jpg,.png,"
            :multiple="false"
            :limit="1"
            :on-exceed="onExceed"
            :file-list="fileList"
            :auto-upload="false"
          >
            <em class="el-icon-plus"></em>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
        v-if="title == '新增签约' || title == '修改签约'"
      >
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <serviceAdd ref="serviceAddDia"></serviceAdd>
  </div>
</template>

<script>
import { inputValidator, selectValidator, IDValid } from "@/utils/validate";
import serviceAdd from "@/views/service/components/service-add.vue";
import { editContract } from "@/api/family_doctor/family_doctor";
import { addFileUrl } from "@/api/followForms/followForms";
const baseApi = process.env.VUE_APP_BASE_API;
import axios from "axios";
export default {
  components: { serviceAdd },
  data() {
    return {
      addDiavisible: false,
      title: "新增签约",
      hospitalUserId: "",
      organizationName: [],
      teamName: [],
      fileList: [],
      addFileUrl: baseApi + addFileUrl,
      ids: [],
      form: {
        id:'',
        sex: "",
        age: "",
        servicePackageIds: "",
      },
      tableData: [],
      sex: [
        {
          id: 0,
          name: "女",
        },
        {
          id: 1,
          name: "男",
        },
      ],
      formRules: {
        groupId: selectValidator,
        serviceStartTime: inputValidator,
        serviceEndTime: inputValidator,
        residentName: inputValidator,
        idCard: IDValid,
        sex: inputValidator,
        age: inputValidator,
        address: inputValidator,
      },
    };
  },
  created() {},
  methods: {
    //关闭
    cancel() {
      for (var key in this.form) {
        this.form[key] = "";
      }
      this.fileList = [];
      this.$refs.tableRef.clearSelection();
      this.$emit("transData");
      this.addDiavisible = false;
    },
    //弹窗渲染之前
    beforeopen() {
      this.hospitalUserId = this.$store.state.name;
      this.$refs.formRef.clearValidate();
    },
    //提交
    addSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请输入必填项!");
        this.form.serviceStartTime = this.dateChange(
          this.form.serviceStartTime
        );
        this.form.serviceEndTime = this.dateChange(this.form.serviceEndTime);
				this.form.serviceEndTime
        await this.uploadImage();
        editContract(this.form).then((res) => {
          if (res.code == "AA000000") {
            this.$message.success(res.msg);
            this.cancel();
          }
        });
      });
    },
    //供父组件调用函数
    openDialog(service, team, title, row) {
      this.tableData = service;
      this.teamName = team;
      this.title = title;
      console.log(title);
      if (title == "查看签约"||title == "修改签约") {
        this.form = row;
        if (this.form.signPhoto != "") {
          let obj = new Object();
          obj.url = baseApi + "/file/" + this.form.signPhoto;
          this.fileList.push(obj);
        }
      }
      this.addDiavisible = true;
    },
    //表格勾选
    tableSelect(selection) {
      this.ids = [];
      selection.forEach((e) => {
        this.ids.push(e.id);
      });
      this.form.servicePackageIds = this.ids.toString();
    },
    //查看详情
    check(row) {
      this.$refs.serviceAddDia.openDialog(false, row, true);
    },
    //状态转换
    formatType(row, column) {
      return row.type == "0" ? "免费" : row.type == "1" ? "付费" : "";
    },
    //计算性别年龄
    sexAndAge(e) {
      this.$refs.formRef.validateField("idCard", (valid) => {
        if (valid) return this.$message.error("请输入正确身份证号!");
        let num = e.target.value;
        if (parseInt(num.substr(16, 1)) % 2 == 1) {
          this.form.sex = 1;
        } else {
          this.form.sex = 0;
        }
        let myDate = new Date();
        let month = myDate.getMonth() + 1;
        let day = myDate.getDate();
        let age = myDate.getFullYear() - num.substring(6, 10) - 1;
        if (
          num.substring(10, 12) < month ||
          (num.substring(10, 12) == month && num.substring(12, 14) <= day)
        ) {
          age++;
        }
        this.form.age = age;
      });
    },
    //上传图片
    async uploadImage() {
      let formData = new FormData();
      if (this.fileList.length > 0) {
        this.fileList.map((item) => {
          formData.append("images", item.raw);
        });
        formData.append("token", this.$store.state.token);
        await axios({
          method: "POST",
          url: this.addFileUrl,
          header: {
            "Content-Type": "multipart/form-data",
          },
          withCredentials: false,
          data: formData,
        }).then((res) => {
          if (res.data.code == "AA000000") {
            this.form.signPhoto = res.data.data;
          }
        });
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    onprogress(file, fileList) {
      this.fileList = fileList;
      const fileSize = file.size / 1024 < 500;
      if (!fileSize) {
        this.$message.warning("不能超过500kb！");
        this.fileList.pop();
      }
    },
    onExceed() {
      this.$message.error("最多上传1个！");
    },
    //转时间戳
    dateChange(date) {
      return new Date(date).getTime();
    },
  },
};
</script>
<style lang="less" scoped>
.buttomItem {
  margin-top: 20px;
}
</style>